package com.cn.qgx428.lazydiary.db

import android.util.Log

import com.j256.ormlite.dao.Dao
import com.j256.ormlite.stmt.QueryBuilder

import java.sql.SQLException

/**
 * Created by QinX on 2017/10/31.
 */

abstract class BaseDao<T> protected constructor() {
    protected lateinit var daoOpe: Dao<T, Int>
    protected var helper: DatabaseHelper

    /**
     * 获取所有
     * @return
     */
    fun getAll(): List<T>?{
        return daoOpe?.queryForAll()
    }

    init {
        helper = DatabaseHelper.newInstance()
        initDao()
    }


    /**
     * 实例化Dao
     */
    protected abstract fun initDao()

    /**
     * 批量添加
     * @param list
     */
    fun addAll(list: List<T>) {
        for (i in list.indices) {
            val id = daoOpe!!.create(list[i])
        }
    }

    /**
     * 单添加
     * @param t
     */
    fun add(t: T) {
        daoOpe!!.create(t)
    }

    /**
     * 通过id删除
     */
    fun delete(id: Int) = daoOpe.deleteById(id)

    /**
     * 更新
     */
    fun update(t: T) = daoOpe.update(t)

    /**
     * 通过名字模糊查询
     */
    fun queryWhereLike(columName: String, value: String): List<T>? {
        var value = value
        value = "%$value%"
        val buider = daoOpe!!.queryBuilder()
        buider.where().like(columName, value)
        return buider.query()
    }

    /**
     * 通过名字模糊查询
     */
    fun queryWhereLikeOrder(columName: String, value: String, order: String, abs: Boolean): List<T>? {
        var value = value
        value = "%$value%"
        val buider = daoOpe!!.queryBuilder()
        buider.orderBy(order, abs)
                .where()
                .like(columName, value)
        return buider.query()
    }

    fun queryByColum(columName: String, value: Any): List<T>? {
        val buider = daoOpe!!.queryBuilder()
        buider.where().like(columName, value)
        return buider.query()
    }

    fun getBuilder() = daoOpe!!.queryBuilder()
}
